<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/15
 * Time: 11:24
 */

namespace app\api\controller;

use think\facade\Db;
use think\Request;

class Cart extends Base
{

    //加入购物车
    public function create(Request $request)
    {
     return json(['code' => 400, 'msg' => '温馨提示：系统临时调整,请稍后']);
        try {
            if ($request->type == 'buy') {
                $this->destory_all($request);
                           //删除当前会员当前立即购买类型的所有数据;
            }

            $data = \app\model\Goods::where('id',$request->goods_id)->find();
            $level_id = \app\model\Member::where('id',$request->member_id)->value('level_id') ?? 0;
            $price = $data['price_'.$level_id];
            $cart_goods = Db::name('cart')->where('goods_id',$request->goods_id)->where('type',$request->type)->where('member_id',$request->member_id)->find();

            if(!empty($cart_goods)){
                Db::name('cart')->where('goods_id',$request->goods_id)->where('type',$request->type)->where('member_id',$request->member_id)->inc('number',$request->number)->update();

                $cart_id = $cart_goods['id'];
            }else{

                $cart_id =Db::name('cart')->insertGetId([
                    'member_id'=>$request->member_id,
                    'goods_id'=>$request->goods_id,
                    'type'=>$request->type,
                    'number'=>$request->number
//                    'price'=>$price
                ]);
            }

            if($request->type == 'buy'){
                return ['code' => 201, 'msg' => '立即购买','cart_id'=> $cart_id];
            }
            if($request->type == 'cart'){
                return ['code' => 200, 'msg' => '加入购物车成功'];
            }

        } catch (\Exception $e) {
             return ['code' => 200, 'msg' => $e->getMessage()];
        }
    }

    public function update_num(Request $request)
    {
        $ret = Db::name('cart')->where('id',$request->cart_id)->update(['number'=>$request->number]);
        return ['code' => 200, 'msg' => '购物车数量修改成功'];
    }



    /**
     * 购物车列表
     */
    public function index(Request $request)
    {

      $data = Db::name('cart')->alias('c')->join('goods g','c.goods_id=g.id')->field('c.goods_id,c.member_id,c.id,c.number,g.title,g.single_pic,g.type_title')->where('member_id',$request->member_id)->where('type',$request->type)->select()->toArray();
       $total_price = 0;
       $total_count = 0;

        foreach ($data as &$v){
            $goods = \app\model\Goods::where('id',$v['goods_id'])->find();

            $level_id = \app\model\Member::where('id',$v['member_id'])->value('level_id') ?? 0;

            $price = $goods['price_'.$level_id];
            $v['price'] = $price;
            $total_price += $v['price']*$v['number'];
            $total_count += $v['number'];

        }
      return ['code' => 200, 'msg' => '购物车列表', 'data' => $data,'total_count'=>$total_count,'total_price'=>$total_price];
    }

    /**商品详情加入购物车
     * @param $goods_id 商品id
     * @param $shop_id 门店id
     * @param $number 商品数量
     * @param $attr_value 属性字符串值 ps."圆形,红色"
     * @return array
     */
    public function create2($goods_id, $shop_id = 0, $number, $attribute = '',$member_id,$type = 'cart')
    {

        try {

            if($type == 'cart_buy_now'){
                //Db::name('cart')->where('type', $type)->where('member_id',$member_id)->delete();
                $this->destory_all($member_id,$type);
                //删除当前会员当前立即购买类型的所有数据;
            }
            $where['goods_id'] = ['eq', $goods_id];
            $where['shop_id'] = ['eq', $shop_id];
            $goods_isset = Db::name('shop_spec_attr')->where($where)->find();
            if (empty($goods_isset)) {
                return ['code' => 0, 'message' => '这个门店的商品不存在'];
            }
            if(empty($attr_value)) $attr_value = '无';
            $where['attribute'] = ['eq', $attr_value];
            if (empty($attr_value)) {
                //return ['code' => 0, 'message' => '不存在无属性商品'];
            }
            $attr_value_isset = Db::name('shop_spec_attr')->where($where)->find();
            if (empty($attr_value_isset)) {
                return ['code' => 0, 'message' => '这个门店商品的属性不存在'];
            }
            $goods_attr_inventory = Db::name('shop_spec_attr')->where($where)->value('inventory');//数据库里的库存
            if ($number > $goods_attr_inventory) {
                return ['code' => 0, 'message' => '购买的商品数量不能大于商品库存'];
            }
            $where['number'] = ['eq', $number];
            //$price = Db::name('shop_goods')->where('id', $goods_id)->value('price');
            $price = Db::name('shop_spec_attr')->where('goods_id', $goods_id)->order('id','asc')->where('attribute',$attr_value)->value('price');

            if($price == 0){
                $price = $price = Db::name('shop_goods')->where('id', $goods_id)->value('price');
            }

            $where['price'] = ['eq', $price];
            $cart_goods_isset = Db::name('cart')->where('goods_id', $goods_id)->where('member_id',$member_id)->where('shop_id',$shop_id)->where('type',$type)->find();//当前会员商品
            if (!empty($cart_goods_isset)) { //如果商品存在就修改数量 如果没有会员id表里没有商品还可以。如果有了。在更换个Id添加立即购买就会走到修改这个方法里bug
                $number = $number+$cart_goods_isset['number'];
                $data = [
                    'goods_id' => $goods_id,
                    'shop_id' => $shop_id,
                    'number' => $number,
                    'price' => $price,
                    'attribute' => $attr_value,
                    'member_id' => $member_id,
                    'type' => $type
                ];
                $ret = Db::name('cart')->where('goods_id',$goods_id)->where('member_id',$member_id)->where('shop_id',$shop_id)->update($data);
                if ($ret !== false) {
                    return ['code' => 200, 'message' => '加入购物车成功'];
                }
                return ['code' => 0, 'message' => '数据修改失败'];
            } else { //反之添加数据
                $data = [
                    'goods_id' => $goods_id,
                    'shop_id' => $shop_id,
                    'number' => $number,
                    'price' => $price,
                    'attribute' => $attr_value,
                    'member_id' => $member_id,
                    'type' => $type
                ];
                $cart_id = Db::name('cart')->insertGetId($data);
                if ($cart_id) {
                    if($type == 'cart'){
                        return ['code' => 200, 'message' => '加入购物车成功'];
                    }
                    if($type == 'cart_buy_now'){
                        return ['code' => 201, 'message' => '立即购买成功','cart_id' => $cart_id];
                    }

                }
                return ['code' => 0, 'message' => '数据添加失败'];
            }
        } catch (\Exception $e) {
            return ['code' => $e->getCode(), 'message' => $e->getMessage()];
        }

    }

    /**
     * @param $member_id
     * @return array
     * 购物车列表
     * 有个price字段 不加加入购物车没意义了就 2种设计
     */
    public static function index2($member_id,$cart_id_string = '',$type)
    {
        $where = [];
        if(!empty($cart_id_string)) $where['c.id'] = ['in',$cart_id_string];
        $cart_list = Db::name('cart')
            ->alias('c')
            ->join('shop s','c.shop_id = s.id','left')
            ->join('shop_goods g','c.goods_id = g.id','left')
            ->where('c.member_id',$member_id)
            ->where('type',$type)
            ->where($where)
            ->field('c.member_id,c.id cart_id,c.goods_id,c.shop_id,c.number,c.price,c.attribute,s.shop_title,s.id shop_id,g.title,g.picUrl thumb_img,g.freight')
            ->select();
        $ret = [];
//        if(!empty($cart_list)){
//            foreach ($cart_list as $k => $v){
//                $ret[$v['shop_id']]['member_id'] = $v['member_id'];
//                $ret[$v['shop_id']]['shop_id'] = $v['shop_id'];
//                $ret[$v['shop_id']]['shop_title'] = $v['shop_title'];
//                $ret[$v['shop_id']]['list'][] = $v;
//                //$ret['shop_title'] = $v['shop_title'];
//                //$ret[$v['shop_id']]['list'][] = $v;
//            }
//        }

        $msg = $type == 'cart' ? '会员购物车列表' : '立即购买列表';
        return ['code' => 200, 'message' => $msg ,'data' => array_values($ret)];
    }

    /**
     * $number = 1,$mark = '+',$cart_id
     * 购物车修改商品数量
     * @param int $number 数量
     * @param string $type + -
     * @param $cart_id
     * @return array
     */
    public function update_number()
    {
        $param = j_decrypt();
        $number = $param['number'];
        $mark = $param['mark'];
        $cart_id = $param['cart_id'];
        //根据cart_id获得goods_id,attribute,shop_id
        $cart_info = Db::name('cart')->find($cart_id);
        $where = [
            'goods_id' => $cart_info['goods_id'],
//            'shop_id' => $cart_info['shop_id'],
            'attribute' => $cart_info['attribute'],
        ];
        $goods_attr_inventory = Db::name('attribute')->where($where)->value('homenum');
        if($mark == '+'){
            if($number+$cart_info['number'] > $goods_attr_inventory){//库存不足
                return j_encrypt(['code' => 400 , 'message' => '要购买的数量大于商品库存']);
            }
            $ret = Db::name('cart')->where('id',$cart_id)->setInc('number',$number);
            if($ret){
                return j_encrypt(['code' => 200 , 'message' => '商品数量相加成功']);
            }
        }else if($mark == '-'){
            if($cart_info['number']-$number > $goods_attr_inventory){//库存不足,别人买了
                return j_encrypt(['code' => 400, 'message' => '要购买的数量大于商品库存-']);
            }
            if($cart_info['number']-$number < 1){//当前购物车数量是1的时候
                return j_encrypt(['code' => 400 , 'message' => '至少购买1个']);
            }
            $ret = Db::name('cart')->where('id',$cart_id)->setDec('number',$number);
            if($ret){
                return j_encrypt(['code' => 200 , 'message' => '商品数量相减成功']);
            }
        }
    }


    /**
     * 购物车商品单一删除
     * @param $cart_id
     * @return array
     */
    public function destory(Request $request)
    {
        $ret = Db::name('cart')->delete($request->cart_id);
        if($ret){
            return ['code' => 200 , 'msg' => 'cart_id '.$request->cart_id.' 商品删除成功'];
        }
        return ['code' => 0 , 'msg' => 'cart_id '.$request->cart_id.' 商品删除失败'];
    }

    /**
     * 清空当前会员购物车
     * @param $member_id
     * @return array
     */
    public function destory_all(Request $request)
    {

        $ret = Db::name('cart')->where(['member_id' => $request->member_id,'type' => $request->type])->delete();
        if ($ret) {
            return ['code' => 200, 'msg' => '购物车已清空'];
        }
        return ['code' => 0, 'msg' => '购物车清空失败'];
    }


}